// pages/labor/edit/edit.js
const app = getApp()

Page({
  data: {
    laborId: null,
    formData: {
      jobTitle: '',
      location: '',
      workType: 'part-time',
      salary: '',
      description: '',
      urgent: false,
      requirements: '',
      qq: '',
      phone: '',
      wechat: '',
      requiredCount: 1,
      typeId: null,
      typeName: ''
    },
    locationOptions: ['校内', '校外', '线上', '市中心', '商业区'],
    originalData: {}, // 保存原始数据用于对比
    hasChanged: false, // 是否有修改
    loading: true
  },

  onLoad(options) {
    if (options.laborId) {
      this.setData({ laborId: options.laborId })
      this.loadLaborDetail(options.laborId)
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载劳务详情
  async loadLaborDetail(laborId) {
    wx.showLoading({ title: '加载中...' })
    
    try {
      const result = await app.utils.request({
        url: `/labor/detail/${laborId}`,
        method: 'GET'
      })
      
      if (result.code === 200) {
        const data = result.data
        
        const formData = {
          jobTitle: data.jobTitle || '',
          location: data.location || '',
          workType: data.workType || 'part-time',
          salary: data.salary ? data.salary.toString() : '',
          description: data.description || '',
          urgent: data.urgent === 1,
          requirements: data.requirements || '',
          qq: data.qq || '',
          phone: data.phone || '',
          wechat: data.wechat || '',
          requiredCount: data.requiredCount || 1,
          typeId: data.typeId,
          typeName: data.typeName || ''
        }
        
        this.setData({
          formData,
          originalData: JSON.parse(JSON.stringify(formData)), // 深拷贝
          loading: false
        })
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: `编辑${data.typeName || '劳务'}`
        })
      } else {
        throw new Error(result.message || '获取劳务详情失败')
      }
    } catch (error) {
      console.error('加载劳务详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
    
    wx.hideLoading()
  },

  // 表单输入处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [`formData.${field}`]: value,
      hasChanged: true
    })
  },

  // 工作地点选择
  onLocationChange(e) {
    const index = e.detail.value
    this.setData({
      'formData.location': this.data.locationOptions[index],
      hasChanged: true
    })
  },

  // 工作类型选择
  onWorkTypeChange(e) {
    const workType = e.currentTarget.dataset.type
    this.setData({
      'formData.workType': workType,
      hasChanged: true
    })
  },

  // 紧急状态切换
  onUrgentChange() {
    this.setData({
      'formData.urgent': !this.data.formData.urgent,
      hasChanged: true
    })
  },

  // 需要人数调整
  onCountChange(e) {
    const action = e.currentTarget.dataset.action
    let count = this.data.formData.requiredCount
    
    if (action === 'decrease' && count > 1) {
      count--
    } else if (action === 'increase' && count < 99) {
      count++
    }
    
    this.setData({
      'formData.requiredCount': count,
      hasChanged: true
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    
    if (!formData.jobTitle.trim()) {
      wx.showToast({
        title: '请输入工作标题',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.location) {
      wx.showToast({
        title: '请选择工作地点',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.salary || isNaN(parseFloat(formData.salary))) {
      wx.showToast({
        title: '请输入有效的薪资',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.description.trim()) {
      wx.showToast({
        title: '请输入工作描述',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  // 提交更新
  async onSubmit() {
    if (!this.validateForm()) {
      return
    }

    if (!this.data.hasChanged) {
      wx.showToast({
        title: '没有修改内容',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '保存中...' })

    try {
      const { formData } = this.data

      const result = await app.utils.request({
        url: `/labor/update`,
        method: 'PUT',
        data: {
          id: this.data.laborId,
          jobTitle: formData.jobTitle,
          location: formData.location,
          workType: formData.workType,
          salary: parseFloat(formData.salary),
          description: formData.description,
          requirements: formData.requirements,
          qq: formData.qq,
          phone: formData.phone,
          wechat: formData.wechat,
          urgent: formData.urgent ? 1 : 0,
          requiredCount: formData.requiredCount,
          typeId: formData.typeId
        }
      })

      wx.hideLoading()

      if (result.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              // 返回上一页并刷新
              wx.navigateBack({
                success: () => {
                  // 通过事件总线通知列表页刷新
                  const pages = getCurrentPages()
                  const prevPage = pages[pages.length - 2]
                  if (prevPage && typeof prevPage.onShow === 'function') {
                    prevPage.onShow()
                  }
                }
              })
            }, 1500)
          }
        })
      } else {
        throw new Error(result.message || '保存失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('更新劳务失败:', error)
      app.utils.showError(error.message || '保存失败')
    }
  },

  // 取消编辑
  onCancel() {
    if (this.data.hasChanged) {
      wx.showModal({
        title: '提示',
        content: '您有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    } else {
      wx.navigateBack()
    }
  },

  // 页面返回拦截
  onUnload() {
    // 页面卸载时的清理工作
  }
})
